<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="就诊卡" prop="cardId">
        <el-input
          v-model="queryParams.cardId"
          placeholder="请输入就诊卡"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="病人姓名" prop="patientName">
        <el-input
          v-model="queryParams.patientName"
          placeholder="请输入病人姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="证件号" prop="number">
        <el-input
          v-model="queryParams.number"
          placeholder="请输入证件号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="注册时间" style="width: 308px">
        <el-date-picker
          v-model="daterangeDate"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['patients:patientlist:patientadd']"
          >新增注册</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['patients:patientlist:patientadd']"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['patients:patientlist:patientadd']"
          >注销</el-button>
        </el-col>
        <!-- <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['patients:patientlist:export']"
          >导出</el-button>
        </el-col> -->
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
  
      <el-table v-loading="loading" :data="patientlistList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <!-- <el-table-column label="病人id" align="center" prop="patientsId" /> -->
        <el-table-column label="就诊卡" align="center" prop="cardId" />
        <el-table-column label="病人姓名" align="center" prop="patientName" />
        <el-table-column label="病人性别" align="center" prop="patientSex">
          <template #default="scope">
            <dict-tag :options="sys_user_sex" :value="scope.row.patientSex"/>
          </template>
        </el-table-column>
        <el-table-column label="病人年龄" align="center" prop="age" />
        <el-table-column label="证件号"   align="center" prop="number"/>
        <el-table-column label="注册时间" align="center" prop="date" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.date, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['patients:patientlist:edit']">修改</el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['patients:patientlist:remove']">删除</el-button>
          </template>
        </el-table-column> -->
      </el-table>
      
      <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
  
      <!-- 添加或修改病人信息对话框 -->
      <el-dialog :title="title" v-model="open" width="500px" append-to-body>
        <el-form ref="patientlistRef" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="就诊卡" prop="cardId">
            <el-input v-model="form.cardId" placeholder="就诊卡号" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="病人姓名" prop="patientName">
            <el-input v-model="form.patientName" placeholder="请输入病人姓名" />
          </el-form-item>
          <el-form-item label="病人性别" prop="patientSex">
            <el-select v-model="form.patientSex" placeholder="请选择病人性别">
              <el-option
                v-for="dict in sys_user_sex"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="病人电话" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入病人手机号" />
          </el-form-item>
          <el-form-item label="病人年龄" prop="age">
            <el-input v-model="form.age" placeholder="请输入病人年龄" />
          </el-form-item>
          <el-form-item label="证件号" prop="number">
            <el-input v-model="form.number" placeholder="请输入证件号" />
          </el-form-item>
          <el-form-item label="联系人姓名" prop="familyName">
            <el-input v-model="form.familyName" placeholder="请输入联系人姓名" />
          </el-form-item>
          <el-form-item label="联系人电话" prop="familyPhone">
            <el-input v-model="form.familyPhone" placeholder="请输入联系人电话"/>
          </el-form-item>
          <el-form-item label="注册时间" prop="date">
            <el-date-picker clearable
              v-model="form.date"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择注册时间">
            </el-date-picker>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup name="Patientlist">
  import { listPatientlist, getPatientlist, delPatientlist, addPatientlist, updatePatientlist } from "@/api/patients/patientlist";
  
  const { proxy } = getCurrentInstance();
  const { sys_user_sex } = proxy.useDict('sys_user_sex');
  
  const patientlistList = ref([]);
  const open = ref(false);
  const loading = ref(true);
  const showSearch = ref(true);
  const ids = ref([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const title = ref("");
  const daterangeDate = ref([]);
 // 自定义验证器
const validatePhone = (rule, value, callback) => {
  if (!value) {
    return callback(new Error('请输入手机号'));
  } else if (!/^1[3456789]\d{9}$/.test(value)) {
    callback(new Error('请输入正确的手机号'));
  } else {
    callback();
  }
};

const validateIdNumber = (rule, value, callback) => {
  if (!value) {
    return callback(new Error('请输入证件号'));
  } else if (!/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(value)) {
    callback(new Error('请输入正确的证件号'));
  } else {
    callback();
  }
};

// 计算年龄的辅助函数
const calculateAge = (idNumber) => {
  if (!/^\d{17}[\dXx]$/.test(idNumber)) {
    return null;
  }
  const birthYear = idNumber.substr(6, 4);
  const birthMonth = idNumber.substr(10, 2);
  const birthDay = idNumber.substr(12, 2);

  const today = new Date();
  const birthDate = new Date(`${birthYear}-${birthMonth}-${birthDay}`);
  
  let age = today.getFullYear() - birthDate.getFullYear();
  const monthDiff = today.getMonth() - birthDate.getMonth();
  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
    age--;
  }

  return age;
};
  
  const data = reactive({
    form: {},
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      cardId: null,
      patientName: null,
      number: null,
      date: null
    },
    rules: {
      patientName: [
        { required: true, message: "病人姓名不能为空", trigger: "blur" }
      ],
      number: [
        { required: true, message: "证件号不能为空", trigger: "blur" },
        { validator: validateIdNumber, trigger: 'blur' }
      ],
      phone: [
        { required: true, message: "病人手机号不能为空", trigger: "blur" },
        { validator: validatePhone, trigger: 'blur' }
      ],
      date: [
        { required: true, message: "注册时间不能为空", trigger: "blur" }
      ],
      age: [
        { required: false, message: "请输入病人年龄", trigger: "blur" },
        { type: 'number', message: '年龄必须为数字值', trigger: 'blur' }
      ]
    }
  });
  
  const { queryParams, form, rules } = toRefs(data);

  
  /** 查询病人信息列表 */
  function getList() {
    loading.value = true;
    queryParams.value.params = {};
    if (null != daterangeDate && '' != daterangeDate) {
      queryParams.value.params["beginDate"] = daterangeDate.value[0];
      queryParams.value.params["endDate"] = daterangeDate.value[1];
    }
    listPatientlist(queryParams.value).then(response => {
      patientlistList.value = response.rows;
      total.value = response.total;
      loading.value = false;
    });
  }
  
  // 取消按钮
  function cancel() {
    open.value = false;
    reset();
  }
  
  // 表单重置
  function reset() {
    form.value = {
      patientsId: null,
      cardId: null,
      patientName: null,
      patientSex: null,
      phone: null,
      age: null,
      number: null,
      familyName: null,
      familyPhone: null,
      date: null
    };
    proxy.resetForm("patientlistRef");
  }
  
  /** 搜索按钮操作 */
  function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
  }
  
  /** 重置按钮操作 */
  function resetQuery() {
    daterangeDate.value = [];
    proxy.resetForm("queryRef");
    handleQuery();
  }
  
  // 多选框选中数据
  function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.patientsId);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
  }
  
  /** 新增按钮操作 */
  function handleAdd() {
    reset();
    open.value = true;
    title.value = "添加病人信息";
  }
  
  /** 修改按钮操作 */
  function handleUpdate(row) {
    reset();
    const _patientsId = row.patientsId || ids.value
    getPatientlist(_patientsId).then(response => {
      form.value = response.data;
      open.value = true;
      title.value = "修改病人信息";
    });
  }
  
  /** 提交按钮 */
  function submitForm() {
    proxy.$refs["patientlistRef"].validate(valid => {
      if (valid) {
        if (form.value.patientsId != null) {
          updatePatientlist(form.value).then(response => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
          });
        } else {
          addPatientlist(form.value).then(response => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
          });
        }
      }
    });
  }
  
  /** 删除按钮操作 */
  function handleDelete(row) {
    const _patientsIds = row.patientsId || ids.value;
    proxy.$modal.confirm('是否确认删除病人信息编号为"' + _patientsIds + '"的数据项？').then(function() {
      return delPatientlist(_patientsIds);
    }).then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    }).catch(() => {});
  }
  
  // 监听证件号变化
  watch(() => form.value.number, (newVal) => {
  if (newVal && newVal.length === 18) {
    const age = calculateAge(newVal);
    if (age !== null) {
      form.value.age = age;
    } else {
      form.value.age = null;
    }
  } else {
    form.value.age = null;
  }
})

  getList();
  </script>
  